let { HttpRequest, globalData, CloudFunction, UserAccess, mfutil , addUserStat } = getApp();
const app = getApp();
let provice = require('./../../provice.json');
let city = require('./../../city.json');
// let area = require('./../../areaCode.json');
let parmas = require('./../../data.json');
Page({
  data: {
    formData: {
      name: '',
      genderCode: '',
      city: '',
      // 区
      // area: '',
      email: '',
      birthDate: ''
    },
    genderCodeIndex: 0,
    genderCodeLists: [{ name: '女', value: 100000002, checked: false }, { name: '男', value: 100000001, checked: false }],
    genderCodeRadio: false,
    userInfo: {},
    currentItem: null,   //Z活跃问卷
    pickerActive: false,
    saveActive: false,
    emailActive: false,  //邮箱填写状态，由值不在允许更改
    userProvince: '',  //提交的省份
    userCity: '',      //提交的城市
    // userArea: '', //提交的区
    value: [0, 0, 0],
    sucvalue: [0, 0],
    getFullYearWar: false,
    getFullYearplace: false,
    question1List: [],
    provice: [],
    city: [],
    // showArea: [],
    // area: [],
    showCity: [{ "name": "北京市", "code": 110100 }],   //默认
    router: '/pages/memberInfo-page/memberInfo-page',
    pagetitle: '用户信息',
    loadingActive: false
  },
  async onLoad() {
    my.hideShareMenu({
      success() {
      },
      fail() {
      },
    });
    this.setData({
      template: parmas.data,
      question1List: parmas.data[0].data,
      ageList: parmas.data[3].ageList,
      sizeList: parmas.data[4].sizeList,
      province: provice.province,
      city: city.city,
      // area: area,
      showCity: city.city[0],
      // showArea: area[city.city[0][0].code],
    })
    console.log(this.data.showArea);

    this.initPage()
  },
  /**
   * 初始化数据
   */
  async initPage() {
    //重新获取会员信息
    let bodyObj1 = {
      "param": globalData.ouid,
      "type": 3
    }
    let path1 = `/vans-family/api/v2.1/project/vansFamily/clm/forward/sendjson/get?url=/v1/member/api/tmall/query`;
    this.setData({
      loadingActive: true
    })
    let res1 = await HttpRequest(path1, 'POST', '', bodyObj1);
    if (res1.data.resultCode == 0) {
      globalData.userInfo = res1.data.data;
      let birthDate = '';
      let { getFullYearplace, getFullYear } = this.data;
      //生日
      let bir = globalData.userInfo.birthDate;
      let dataTime = '';
      dataTime = globalData.userInfo.brandTenure;
      if (bir) {//存在生日
        if (bir.split('/')[0] != 'null') {  //全
          if (bir.length > 5) {
            birthDate = bir.replace(/\//g, '-');
            getFullYear = true;
            getFullYearplace = true;
          } else {  //却少年份
            birthDate = '-' + bir.replace(/\//g, '-');
            getFullYear = false;
          }
        }
      } else {//不存在生日
        getFullYearplace = true;
        getFullYear = false;
      }
      //省份
      let { province, city } = this.data;
      let provinceIndex = '';
      if (globalData.userInfo.province) {
        provinceIndex = province.findIndex((item) => {
          return item.name == globalData.userInfo.province
        })
      }
      let cityIndex = '';
      if (globalData.userInfo.city) {
        cityIndex = city[provinceIndex].findIndex((item) => {
          return item.name == globalData.userInfo.city
        })
      }
      globalData.userInfo.userProvinceCode = globalData.userInfo.provinceId || '';
      globalData.userInfo.userCityCode = globalData.userInfo.cityId || '';
      // globalData.userInfo.userAreaCode = globalData.userInfo.areaCodeId || '';
      this.setData({
        userInfo: globalData.userInfo,
        formData: {
          name: globalData.userInfo.fullName,
          genderCode: globalData.userInfo.genderCode == 100000000 ? "" : globalData.userInfo.genderCode,
          city: globalData.userInfo.province == globalData.userInfo.city ? globalData.userInfo.city : (globalData.userInfo.province ? globalData.userInfo.province : '') + ' ' + (globalData.userInfo.city ? globalData.userInfo.city : ''),
          email: globalData.userInfo.email,
          birthDate
        },
        genderCodeIndex: globalData.userInfo.genderCode == 100000001 ? 1 : 0,
        dataTime,
        userProvince: globalData.userInfo.province,
        userCity: globalData.userInfo.city,
        showCityIndex: cityIndex,
        provinceIndex: provinceIndex,
        getFullYearplace,
        getFullYear,
        emailActive: globalData.userInfo.email ? true : false,
      })
      let { userInfo, question1List } = this.data;
      let interestsZN = {}
      for (let value of question1List) {
        for (let i in userInfo.interests) {
          if (i == value.sync_clm_value) {
            interestsZN[value.desc] = '1'
          }
        }
      }
      this.setData({
        interestsZN
      })
      this.setData({
        loadingActive: false
      })
    } else {
      my.alert({
        content: res.data.resultDesc
      })
    }
  },
  /**
   * input框记录
   * @param {*} event 
   */
  inputRecord(event) {
    let { value } = event.detail;
    let { item } = event.currentTarget.dataset;
    if (item == 'formData.email') {
      value = value.replace(/[^0-9A-Za-z@-_\.\/-]/g, '');
    }
    this.setData({
      [item]: value,
    })
    this.saveActiveFn(true)
  },
  saveActiveFn(event) {
    this.setData({
      saveActive: Boolean(event)
    })
  },
  /**
   * input框失去焦点
   * @param {*} event 
   */
  inputBlur(event) {
    let { value } = event.detail;
    let { item } = event.currentTarget.dataset;
    if (item == 'formData.email') {
      let reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (!reg.test(value) && value != '') {
        my.showToast({
          content: '请填写正确格式邮箱',
          duration: 1000
        });
      } else {
        globalData.userInfo.email = value;
      }
    }
    this.setData({
      [item]: value,
    })
  },
  birthDateFn() {
    this.setData({
      pickerActive: false
    })
    let item = 'formData.birthDate';
    let { birthDate } = this.data.formData;
    let time = new Date();
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var cy = new Date(birthDate).getFullYear();
    var cm = new Date(birthDate).getMonth() + 1;
    var cd = new Date(birthDate).getDate();
    my.datePicker({
      format: 'yyyy-MM-dd',
      currentDate: `${y - 16}-${m}-${d}`,
      startDate: '1960-01-01',
      endDate: `${y - 16}-${m}-${d}`,
      success: (res) => {
        let sy = new Date(res.date).getFullYear();
        let sm = new Date(res.date).getMonth() + 1;
        ((sm / 10) < 1) ? sm = `0${sm}` : sm = sm;
        let sd = new Date(res.date).getDate();
        ((sd / 10) < 1) ? sd = `0${sd}` : sd = sd;
        if (Number(sy) > (Number(y) - 16)) {
          my.alert({
            content: '加入会员必须年满16周岁以上'
          })
        }
        this.setData({
          [item]: `${sy}/${sm}/${sd}`,
          // saveActive: true,
          getFullYearplace: true
        })
        this.saveActiveFn(true)
        globalData.userInfo.birthDate = `${sy}/${sm}/${sd}`;
      },
    });
  },
  /**
  * 性别选择改变
  */
  onChangegenderCode(event) {
    my.hideKeyboard();
    let { genderCodeLists } = this.data;
    this.setData({
      genderCode: genderCodeLists[event.detail.value].value,
      genderCodeIndex: event.detail.value[0],
    })
  },
  successBtn() {
    let item = 'formData.genderCode';
    let { genderCode, genderCodeIndex, genderCodeLists } = this.data;
    this.setData({
      [item]: genderCodeLists[genderCodeIndex].value,
      genderCodeRadio: false,
      saveActive: true
    })

  },
  failBtn() {
    this.setData({
      genderCodeRadio: false
    })
  },
  /**
   * 提交个人信息
   */
  async saveFn() {

    let { userProvince, userCity, userArea, formData, userProvinceCode, userCityCode, userAreaCode } = this.data;
    let path = `/vans-family/api/v2.1/project/vansFamily/clm/forward?url=/v1/member/api/tmall/update&type=PUT`;
    let birthDate = formData.birthDate.replace(/\-/g, '/');
    let bodyObj = {
      "memberId": globalData.userInfo.memberId,
      "fullName": formData.name,
      "genderCode": formData.genderCode,
      "birthDate": birthDate,
      "email": formData.email,
      "shoeSize": globalData.userInfo.shoeSize,
      "brandTenure": globalData.userInfo.brandTenure,   //品牌生命周期
      "provinceId": userProvinceCode,
      "province": userProvince,
      "cityId": userCityCode,
      // "areaCodeId": userAreaCode,
      "city": userCity,
      // "area":userArea,
      "interests": globalData.userInfo.interests
    }
    console.log(bodyObj);

    let a = formData.birthDate.split('');
    //邮箱校验
    if (formData.email) {
      let reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (!reg.test(formData.email) && formData.email != '') {
        my.showToast({
          content: '请填写正确格式邮箱',
          duration: 1000
        });
        return
      }
    }
    let res = await HttpRequest(path, 'POST', '', bodyObj);
    if (res.data.resultCode == 0) {
      my.showToast({
        type: 'success',
        content: '保存成功',
        duration: 1000,
        success: () => {
          this.setData({
            // saveActive: false,
            pickerActive: false
          })
          this.saveActiveFn(false)
          this.initPage()
        },
        fail: () => {
        }
      });
    } else {
      my.alert({
        content: res.data.resultDesc
      })
    }
    /**
   * 用户行为记录埋点
   */
    let routerArr = getCurrentPages();
    let options = {
      grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
      name: routerArr[routerArr.length - 1].data.pagetitle,
    }
    let track = UserAccess(options)

    // 自定义埋点
    let customAccessoptions = {
      customType: '更新个人信息'
    }
    console.log('更新个人信息');
    
    let tracks = addUserStat(customAccessoptions)
  },
  focus() {
    this.setData({
      pickerActive: false
    })
  },
  genderCodeFn() {
    my.hideKeyboard();
    this.setData({
      genderCodeRadio: true
    })
  },
  /**
   * 省市遮罩点击
   */
  cityChange() {
    my.hideKeyboard();
    let { pickerActive, value } = this.data;
    this.setData({
      pickerActive: !pickerActive,   //弹窗改变
      // userProvince: this.data.province[value[0]],
      // userCity: this.data.city[value[0]][value[1]],
      value
    })
  },
  exitChangeSuc() {
    let { pickerActive } = this.data;
    this.setData({
      pickerActive: !pickerActive,   //弹窗改变   
    })
  },
  /**
   * 提交省份
   */
  cityChangeSuc() {

    let { pickerActive, userProvince, userCity, value, city, province, area } = this.data;
    console.log(province[value[0]].name , city[value[0]][value[1]].name );
    globalData.userInfo.province = province[value[0]].name;
    globalData.userInfo.city = city[value[0]][value[1]].name;
    // globalData.userInfo.area = area[this.data.city[value[0]][value[1]].code][value[2]].item_name;
    globalData.userInfo.userProvinceCode = province[value[0]].code;
    globalData.userInfo.userCityCode = city[value[0]][value[1]].code;
    // globalData.userInfo.userAreaCode = area[this.data.city[value[0]][value[1]].code][value[2]].item_code;
    let item = 'formData.city'


    this.setData({
      pickerActive: !Boolean(pickerActive),   //弹窗改变
      [item]: province[value[0]].name == city[value[0]][value[1]].name ? city[value[0]][value[1]].name : province[value[0]].name + city[value[0]][value[1]].name,
      userProvince: province[value[0]].name,
      userCity: city[value[0]][value[1]].name,
      // userArea: area[this.data.city[value[0]][value[1]].code][value[2]].item_name,
      // userAreaCode: area[this.data.city[value[0]][value[1]].code][value[2]].item_code,
      userProvinceCode: province[value[0]].code,
      userCityCode: city[value[0]][value[1]].code,
      // saveActive: true,
      sucvalue: value
    })
    console.log(item);

    this.saveActiveFn(true)
  },
  /**
   * 省份选择
   *  */
  onChange(e) {
    let value = !this.data.city[e.detail.value[0]][e.detail.value[1]] ? [e.detail.value[0], 0] : e.detail.value;
    this.setData({
      value,
      showCity: this.data.city[value[0]],
      // showArea: this.data.area[this.data.city[value[0]][value[1]].code],
      // userProvince: this.data.province[value[0]].name,
      // userCity: this.data.city[value[0]][value[1]].name,
      // userArea: this.data.area[this.data.city[value[0]][value[1]].code][value[2]]
    });
    console.log(this.data.userProvince, 'userProvinceuserProvinceuserProvince')
  },
  /**
   * 问卷跳转
   * @a a取消
   */
  openQuest(event, a) {
    let item = null;
    if (event) {
      item = event.currentTarget.dataset.item;
    }
    if (!a) {
      this.initPage();
    }
    this.setData({
      currentItem: item,
      saveActive: false
    })
  },
  /**
   * 链接跳转
   */
  navigateToOutside() {
    my.call("navigateToOutside", {
      url: "https://vans.com/vansfamily"
    })
  },
  /**
   * 积分历史记录
   */
  navigateChange() {
    my.navigateTo({
      url: '/pages/task-page/task-page'
    });
  },
  wangwang() {
    my.tb.openMessage({
      sellerNick: "vans官方旗舰店",
      success: (res) => {
      },
      fail: (res) => {
      },
    })
  }
});
